package com.kabuda.zhugehot200;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author kabuda
 * @date 2025-03-16 16:18
 * @description
 */
public class t11_二叉树的最小深度 {
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode6 = new TreeNode(6);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;

        treeNode3.left = treeNode4;
        treeNode4.left = treeNode5;

        System.out.println(dfs(treeNode1));
        System.out.println(bfs(treeNode1));
    }


    /**
     * @param root
     * @author kabuda
     * @date 2025/3/16 16:36
     * @description 深度优先遍历
     */
    public static int dfs(TreeNode root) {
        //根节点为空,则为0
        if (root == null) {
            return 0;
        }

        //如果是叶子节点,就是1
        if (root.left == null && root.right == null) {
            return 1;
        }

        int min = Integer.MAX_VALUE;

        //如果为空,就不要进去了,不然返回的是0
        if (root.left != null) {
            min = Math.min(dfs(root.left), min);
        }
        //如果为空,就不要进去了,不然返回的是0
        if (root.right != null) {
            min = Math.min(dfs(root.right), min);
        }

        return min + 1;
    }

    /**
     * @param root
     * @author kabuda
     * @date 2025/3/16 16:36
     * @description 广度优先遍历
     */
    public static int bfs(TreeNode root) {
        //根节点为空,则为0
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        //将根节点入队
        //将节点的值当作深度(也可加一个字段1)
        root.val = 1;
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            //找到第一个叶子节点,这就是的最小深度
            if (node.left == null && node.right == null) {
                return node.val;
            }

            if (node.left != null) {
                node.left.val = node.val + 1;
                queue.add(node.left);
            }

            if (node.right != null) {
                node.right.val = node.val + 1;
                queue.add(node.right);
            }
        }
        return 0;
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


}
